package com.heima.wemedia.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.pojos.WmUserVO;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import com.heima.wemedia.pojo.vo.LoginVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Override
    public ResponseResult login(WmLoginDto dto) {
        //1.参数校验,健壮性校验
        String name = dto.getName();
        String password = dto.getPassword();
        if (StrUtil.isBlank(name)|| StrUtil.isBlank(password)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.根据用户名查询用户
        WmUser user = lambdaQuery().eq(WmUser::getName, name).one();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        //3.校验密码
        boolean checkpw = BCrypt.checkpw(dto.getPassword(), user.getPassword());
        if (!checkpw){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        } else {
            LoginVO loginVO = new LoginVO();

            //3.生成jwt令牌
            String token = AppJwtUtil.getToken(Long.valueOf(user.getId()));
            loginVO.setToken(token);
            WmUserVO wmUserVO = new WmUserVO();
            BeanUtils.copyProperties( user,wmUserVO);
            wmUserVO.setCreatedTime(user.getCreatedTime().getTime());
            wmUserVO.setPassword("");
            loginVO.setUser(wmUserVO);

            return ResponseResult.okResult(loginVO);
        }
    }
}